package com.browsesoft.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import com.browsesoft.PropertiesService;

public class TempFileFactory {

	private static TempFileFactory self = new TempFileFactory();

	private List tempFiles;

	private int fileCount = 0;

	private int maxCount;

	private String filePath;

	private TempFileFactory() {
		this.tempFiles = new LinkedList();
		// 根据配置的初始化数目构造临时文件，放入tempFiles
		String initCount = "";
		String maxCount = "";
		try {
			initCount = PropertiesService.getProperty("tempFile", "initCount");
			maxCount = PropertiesService.getProperty("tempFile", "maxCount");
			this.filePath = PropertiesService.getProperty("tempFile",
					"filePath");
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		this.maxCount = Integer.parseInt(maxCount);
		int iCount = Integer.parseInt(initCount);
		for (int i = 0; i < iCount; i++) {
			this.tempFiles.add(this.createFile(fileCount));
		}
	}

	/**
	 * 构造新的临时文件
	 * 
	 * @param fileCount
	 * @return
	 */
	private File createFile(int fileCount) {
		File path = new File(this.filePath);
		if (!path.exists()) {
			path.mkdir();
		}
		File tempFile = new File(this.filePath + "tempFile" + fileCount);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(tempFile);
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		fileCount++;
		this.fileCount = fileCount;
		return tempFile;
	}

	/**
	 * 回收临时文件
	 * 
	 * @param file
	 */
	public synchronized void put(File file) {
		boolean addSuccess = this.tempFiles.add(file);
		if (addSuccess) {
			notifyAll();
		}
	}

	/**
	 * 得到临时文件
	 * 
	 * @return
	 */
	public synchronized File getFile() {
		if (!this.tempFiles.isEmpty()) {
			return (File) this.tempFiles.remove(0);
		} else {
			if (this.fileCount < this.maxCount) {
				// 构造新的临时文件并返回
				return this.createFile(this.fileCount);
			} else {
				try {
					while (this.tempFiles.isEmpty()) {
						wait();
					}
					return (File) this.tempFiles.remove(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
	}

	/**
	 * 得到单例
	 * 
	 * @return
	 */
	public static TempFileFactory getInstance() {
		if (self == null) {
			self = new TempFileFactory();
			return self;
		}
		return self;
	}
}
